package com.css.zfzx.fxpg.common.platform;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.components.attach.viewobjects.SaveAttachmentVO;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.fxpg.common.utils.FileToByteUtil;

import java.io.IOException;
import java.util.List;

/**
 * 通过平台接口获取信息的封装
 *
 * @author leon
 * @date 2020/11/5 14:38
 */
public class Platform {

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    public static UserEntity getUser() {
        String userId = PlatformSessionUtils.getUserId();
        PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        return user;
    }

    /**
     * 上传附件
     *
     * @param attachPath 附件全路径，如：c:\附件.doc
     * @return
     */
    public static SaveAttachmentVO uploadAttach(String attachPath) {
        SaveAttachmentVO attachmentVO = new SaveAttachmentVO();
        try {
            attachmentVO.setAttachId(UUIDGenerator.getUUID());
            attachmentVO.setAttachMd5(attachmentVO.getAttachId());
            String attachName = attachPath.substring(attachPath.lastIndexOf("\\") + 1);
            attachmentVO.setAttachName(attachName);
            // 截取‘.’位置，获取类型
            attachmentVO.setAttachType(attachName.substring(attachName.indexOf(".") + 1));
            byte[] bytes = FileToByteUtil.fileToByte(attachPath);
            attachmentVO.setFile(bytes);
            attachmentVO.setFileDirId("defaultDirectory");
            PlatformAPI.getAttachmentAPI().saveFile(attachmentVO);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return attachmentVO;
    }

    /**
     * 根据字典项名称获取字典项编码
     *
     * @param dictItemName
     * @param dictCode
     * @return
     */
    public static String getDictItemCode(String dictItemName, String dictCode) {
        String dictItemCode = "";
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        for (DictItemEntity dictItemEntity :
                validDictItems) {
            if (dictItemName.equals(dictItemEntity.getDictItemName())) {
                dictItemCode = dictItemEntity.getDictItemCode();
                break;
            }
        }
        return dictItemCode;
    }
}
